package jehc.djshi.sys.web;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jehc.djshi.common.annotation.NeedLoginUnAuth;
import jehc.djshi.common.base.*;
import jehc.djshi.common.entity.ConstantEntity;
import jehc.djshi.common.entity.DataDictionaryEntity;
import jehc.djshi.common.entity.UserinfoEntity;
import jehc.djshi.common.util.MD5;
import jehc.djshi.common.util.JsonUtil;
import jehc.djshi.common.util.RestTemplateUtil;
import jehc.djshi.common.util.StringUtil;
import jehc.djshi.common.base.*;
import jehc.djshi.oauth.dao.OauthAccountDao;
import jehc.djshi.oauth.model.OauthAccount;
import jehc.djshi.oauth.service.OauthAccountService;
import jehc.djshi.sys.model.XtUserinfo;
import jehc.djshi.sys.service.XtUserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageInfo;

/**
 * @Desc 员工信息
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@RestController
@RequestMapping("/xtUserinfo")
@Api(value = "员工信息API",tags = "员工信息API",description = "员工信息API")
public class XtUserinfoController extends BaseAction {
	@Autowired
	private XtUserinfoService xtUserinfoService;
	@Autowired
	OauthAccountService oauthAccountService;
	@Autowired
	CommonUtils commonUtils;

	/**
	* 加载初始化列表数据并分页
	* @param baseSearch
	*/
	@NeedLoginUnAuth
	@PostMapping(value="/list")
	@ApiOperation(value="查询员工信息列表并分页", notes="查询员工信息列表并分页")
	public BasePage getXtUserinfoListByCondition(@RequestBody(required=true)BaseSearch baseSearch){
		Map<String, Object> condition = baseSearch.convert();
		commonHPager(baseSearch);
		List<XtUserinfo>XtUserinfoList = xtUserinfoService.getXtUserinfoListByCondition(condition);
		PageInfo<XtUserinfo> page = new PageInfo<XtUserinfo>(XtUserinfoList);
		return outPageBootStr(page,baseSearch);
	}
	
	/**
	 * 已删除用户
	 * @param baseSearch
	 * @return
	 */
	@PostMapping(value="/deleted/list")
	@NeedLoginUnAuth
	@ApiOperation(value="查询已删除用户列表并分页", notes="查询已删除用户列表并分页")
	public BasePage getXtUserinfoDeletedListByCondition(@RequestBody(required=true)BaseSearch baseSearch){
		Map<String, Object> condition = baseSearch.convert();
		commonHPager(baseSearch);
		List<XtUserinfo>XtUserinfoList = xtUserinfoService.getXtUserinfoDeletedListByCondition(condition);
		PageInfo<XtUserinfo> page = new PageInfo<XtUserinfo>(XtUserinfoList);
		return outPageBootStr(page,baseSearch);
	}
	
	/**
	* 查询单个用户
	* @param xt_userinfo_id
	*/
	@GetMapping(value="/get/{xt_userinfo_id}")
	@NeedLoginUnAuth
	@ApiOperation(value="查询单个用户", notes="查询单个用户")
	public BaseResult getXtUserinfoById(@PathVariable("xt_userinfo_id")String xt_userinfo_id){
		XtUserinfo xt_Userinfo = xtUserinfoService.getXtUserinfoById(xt_userinfo_id);
		return outDataStr(xt_Userinfo);
	}
	
	/**
	* 添加
	* @param xtUserinfo
	*/
	@PostMapping(value="/add")
	@ApiOperation(value="创建单个用户", notes="创建单个用户")
	public BaseResult addXtUserinfo(@RequestBody XtUserinfo xtUserinfo, HttpServletRequest request){
		int i = 0;
		MD5 md5 = new MD5();
		if(null != xtUserinfo){
			xtUserinfo.setXt_userinfo_id(toUUID());
			ConstantEntity constantEntity = commonUtils.getXtConstantCache("XtUserinfoDefaultPwd");
			xtUserinfo.setXt_userinfo_passWord(md5.getMD5ofStr(constantEntity.getValue()));
			i=xtUserinfoService.addXtUserinfo(xtUserinfo);
		}
		if(i>0){
			aBLogs("用户控制层", "添加", "添加用户成功");
			return outAudStr(true);
		}else{
			aBLogs("用户控制层", "添加", "添加用户失败");
			return outAudStr(false);
		}
	}
	
	/**
	* 修改
	* @param xtUserinfo
	*/
	@PutMapping(value="/update")
	@ApiOperation(value="编辑单个用户", notes="编辑单个用户")
	public BaseResult updateXtUserinfo(@RequestBody XtUserinfo xtUserinfo){
		int i = 0;
		if(null != xtUserinfo){
			i=xtUserinfoService.updateXtUserinfo(xtUserinfo);
		}
		if(i>0){
			aBLogs("用户控制层", "修改", "修改用户成功");
			return outAudStr(true);
		}else{
			aBLogs("用户控制层", "修改", "修改用户失败");
			return outAudStr(false);
		}
	}
	
	/**
	* 删除
	* @param xt_userinfo_id
	*/
	@DeleteMapping(value="/delete")
	@ApiOperation(value="删除用户", notes="删除用户")
	public BaseResult delXtUserinfo(String xt_userinfo_id){
		int i = 0;
		if(!StringUtil.isEmpty(xt_userinfo_id)){
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("xt_userinfo_id",xt_userinfo_id.split(","));
			i=xtUserinfoService.delXtUserinfo(condition);
		}
		if(i>0){
			aBLogs("用户控制层", "删除", "删除用户成功");
			return outAudStr(true);
		}else{
			aBLogs("用户控制层", "删除", "删除用户失败");
			return outAudStr(false);
		}
	}
	
	/**
	 * 获取名族数据字典
	 * @param request
	 */
	@NeedLoginUnAuth
	@GetMapping(value="/nation/list")
	@ApiOperation(value=" 获取名族数据字典", notes=" 获取名族数据字典")
	public BaseResult getXtUserinfoNationList(HttpServletRequest request){
		List<DataDictionaryEntity> dataDictionaryEntities = commonUtils.getXtDataDictionaryCache("xt_userinfo_nation");
		return outComboDataStr(dataDictionaryEntities);
	}
	
	/**
	 * 获取性别数据字典
	 * @param request
	 */
	@NeedLoginUnAuth
	@GetMapping(value="/sex/list")
	@ApiOperation(value=" 获取性别数据字典", notes=" 获取性别数据字典")
	public BaseResult getXtUserinfoSexList(HttpServletRequest request){
		List<DataDictionaryEntity> dataDictionaryEntities = commonUtils.getXtDataDictionaryCache("gender");
		return outComboDataStr(dataDictionaryEntities);
	}
	
	/**
	 * 获取文化程度数据字典
	 * @param request
	 */
	@NeedLoginUnAuth
	@GetMapping(value="/highestdegree/list")
	@ApiOperation(value=" 获取文化程度数据字典", notes=" 获取文化程度数据字典")
	public BaseResult getXtUserinfoHighestDegreeList(HttpServletRequest request){
		List<DataDictionaryEntity> dataDictionaryEntities = commonUtils.getXtDataDictionaryCache("xt_userinfo_highestDegree");
		return outComboDataStr(dataDictionaryEntities);
	}
	
	/**
	 * 获取工作年限数据字典
	 * @param request
	 */
	@NeedLoginUnAuth
	@GetMapping(value="/workyear/list")
	@ApiOperation(value=" 获取工作年限数据字典", notes=" 获取工作年限数据字典")
	public BaseResult getXtUserinfoWorkYearList(HttpServletRequest request){
		List<DataDictionaryEntity> dataDictionaryEntities = commonUtils.getXtDataDictionaryCache("xt_userinfo_workYear");
		return outComboDataStr(dataDictionaryEntities);
	}
	
	/**
	 * 获取是否已婚数据字典
	 * @param request
	 */
	@NeedLoginUnAuth
	@GetMapping(value="/ismarried/list")
	@ApiOperation(value=" 获取是否已婚数据字典", notes=" 获取是否已婚数据字典")
	public BaseResult getXtUserinfoIsmarriedList(HttpServletRequest request){
		List<DataDictionaryEntity> dataDictionaryEntities = commonUtils.getXtDataDictionaryCache("xt_userinfo_ismarried");
		return outComboDataStr(dataDictionaryEntities);
	}
	
	/**
	 * 获取用户状态数据字典
	 * @param request
	 */
	@NeedLoginUnAuth
	@GetMapping(value="/state/list")
	@ApiOperation(value=" 获取用户状态数据字典", notes=" 获取用户状态数据字典")
	public BaseResult getXtUserinfoStateList(HttpServletRequest request){
		List<DataDictionaryEntity> dataDictionaryEntities = commonUtils.getXtDataDictionaryCache("xt_userinfo_state");
		return outComboDataStr(dataDictionaryEntities);
	}
	
	/**
	 * 判断用户名即登陆账号是否重复
	 * @param xt_userinfo_name
	 */
	@NeedLoginUnAuth
	@GetMapping(value="/validate/{xt_userinfo_name}")
	@ApiOperation(value=" 判断用户名即登陆账号是否重复", notes=" 判断用户名即登陆账号是否重复")
	public BaseResult validateUser(@PathVariable("xt_userinfo_name")String xt_userinfo_name){
		Map<String, Object> condition = new HashMap<String, Object>();
		if(!StringUtil.isEmpty(xt_userinfo_name)){
			condition.put("xt_userinfo_name", xt_userinfo_name);
			int i = xtUserinfoService.validateUser(condition);
			if(i > 0){
				return outAudStr(true,"1");
			}else{
				return outAudStr(true,"0");
			}
		}else{
			return outAudStr(false,"用户名参数未获取!验证失败!");
		}
	}
	
	/**
	* 恢复数据
	* @param xt_userinfo_id
	*/
	@GetMapping(value="/recover")
	@ApiOperation(value=" 恢复数据", notes=" 恢复数据")
	public BaseResult recoverXtUserinfo(String xt_userinfo_id){
		int i = 0;
		if(!StringUtil.isEmpty(xt_userinfo_id)){
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("xt_userinfo_id",xt_userinfo_id.split(","));
			i=xtUserinfoService.recoverXtUserinfo(condition);
		}
		if(i>0){
			aBLogs("用户控制层", "恢复用户", "恢复用户成功");
			return outAudStr(true);
		}else{
			aBLogs("用户控制层", "恢复用户", "恢复用户失败");
			return outAudStr(false);
		}
	}

	
	/**
	 * 
	 * @param request
	 * @return
	 */
	@NeedLoginUnAuth
	@GetMapping(value="/chatting/list")
	@ApiOperation(value=" 全部用户", notes=" 全部用户")
	public BaseResult getChattingUserinfoList(HttpServletRequest request){
		Map<String, Object> condition = new HashMap<String, Object>();
		List<BaseTreeGridEntity> list = new ArrayList<BaseTreeGridEntity>();
		List<XtUserinfo> XtUserinfoList = xtUserinfoService.getXtUserinfoListByCondition(condition);
		for(int i = 0; i < XtUserinfoList.size(); i++){
			XtUserinfo Xt_Userinfo = XtUserinfoList.get(i);
			BaseTreeGridEntity BaseTreeGridEntity = new BaseTreeGridEntity();
			BaseTreeGridEntity.setId(Xt_Userinfo.getXt_userinfo_id());
			BaseTreeGridEntity.setPid("0");
			BaseTreeGridEntity.setText(Xt_Userinfo.getXt_userinfo_realName());
			BaseTreeGridEntity.setContent("");
			BaseTreeGridEntity.setLeaf(true);
			BaseTreeGridEntity.setIcon("/deng/images/icons/employee_manager.png");
			list.add(BaseTreeGridEntity);
		}
		BaseTreeGridEntity baseTreeGridEntity = new BaseTreeGridEntity();
		List<BaseTreeGridEntity> baseTreeGridEntityList = baseTreeGridEntity.buildTree(list,"0");
		String json = JsonUtil.toFastJson(baseTreeGridEntityList);
		return outStr(json);
	}

	/**
	 * 重置密码
	 * @param xt_userinfo_id
	 * @return
	 */
	@GetMapping(value="/pwd/reset")
	@ApiOperation(value=" 重置密码", notes=" 重置密码")
	public BaseResult resetXtUserinfoPwd(String xt_userinfo_id,HttpServletRequest request){
		int i = 0;
		MD5 md5 = new MD5();
		if(!StringUtils.isEmpty(xt_userinfo_id)){
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("xt_userinfo_id",xt_userinfo_id);
			ConstantEntity constantEntity = commonUtils.getXtConstantCache("XtUserinfoDefaultPwd");
			condition.put("xt_userinfo_passWord", md5.getMD5ofStr(constantEntity.getValue()));
			i=xtUserinfoService.updatePwd(condition);
		}
		XtUserinfo user = xtUserinfoService.getXtUserinfoById(xt_userinfo_id);
		if(i>0){
			aBLogs("用户控制层", "重置用户密码", "重置用户密码，用户名：【"+user.getXt_userinfo_name()+"】用户姓名：【"+user.getXt_userinfo_realName()+"】成功");
			return outAudStr(true);
		}else{
			aBLogs("用户控制层", "重置用户密码", "重置用户密码，用户名：【"+user.getXt_userinfo_name()+"】用户姓名：【"+user.getXt_userinfo_realName()+"】失败");
			return outAudStr(false);
		}
	}
	
	/**
	 * 根据各种情况查找集合不分页（流程设计器中处理人 发起人 发起人组等使用）
	 * @param xt_userinfo_id
	 * @return
	 */
	@NeedLoginUnAuth
	@GetMapping(value="/lc/list/{xt_userinfo_id}")
	@ApiOperation(value=" 根据各种情况查找集合不分页", notes=" 根据各种情况查找集合不分页")
	public BaseResult getXtUserinfoList(@PathVariable("xt_userinfo_id")String xt_userinfo_id){
		List<XtUserinfo> list = new ArrayList<XtUserinfo>();
		if(null != xt_userinfo_id && !"".equals(xt_userinfo_id)){
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("xt_userinfo_id", xt_userinfo_id.split(","));
			list = xtUserinfoService.getXtUserinfoList(condition);
		}
		return  outItemsStr(list);
	}
	
//	/**
//	* 修改（个人中心）
//	* @param xt_Userinfo
//	*/
//	@NeedLoginUnAuth
//	@PutMapping(value="/myinfo/update")
//	public BaseResult updateMyXtUserinfo(XtUserinfo xt_Userinfo){
//		int i = 0;
//		UserinfoEntity userinfoEntity = getXtU();
//		XtUserinfo xtUserinfo = new XtUserinfo();
//		BeanUtils.copyProperties(userinfoEntity, xtUserinfo);//拷贝
//
//		if(null == xtUserinfo){
//			throw new ExceptionUtil("未能获取到当前用户！");
//		}
//		if(null != xt_Userinfo && !"".equals(xt_Userinfo)){
//			xtUserinfo.setXt_userinfo_phone(xt_Userinfo.getXt_userinfo_phone());
//			xtUserinfo.setXt_userinfo_mobile(xt_Userinfo.getXt_userinfo_mobile());
//			xtUserinfo.setXt_userinfo_ortherTel(xt_Userinfo.getXt_userinfo_ortherTel());
//			xtUserinfo.setXt_userinfo_qq(xt_Userinfo.getXt_userinfo_qq());
//			xtUserinfo.setXt_userinfo_email(xt_Userinfo.getXt_userinfo_email());
//			xtUserinfo.setXt_userinfo_remark(xt_Userinfo.getXt_userinfo_remark());
//			xtUserinfo.setXt_userinfo_address(xt_Userinfo.getXt_userinfo_address());
//			i=xtUserinfoService.updateXtUserinfo(xtUserinfo);
//		}
//		if(i>0){
//			aBLogs("用户控制层", "修改", "修改用户成功");
//			return outAudStr(true);
//		}else{
//			aBLogs("用户控制层", "修改", "修改用户失败");
//			return outAudStr(false);
//		}
//	}
	
	/**
	* myinfo
	*/
	@GetMapping(value="/myinfo")
	@NeedLoginUnAuth
	@ApiOperation(value=" 当前用户信息", notes=" 当前用户信息")
	public BaseResult myinfo(){
		return outDataStr(getXtU());
	}
	
	/**
	 * 流程模块使用（查找用户）
	 * @param baseSearch
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@PostMapping(value="/lc/list")
	@NeedLoginUnAuth
	@ApiOperation(value=" 流程模块使用", notes=" 流程模块使用")
	public BasePage getXtUserinfoListForLcByCondition(@RequestBody(required=true)BaseSearch baseSearch){
		Map<String, Object> condition = baseSearch.convert();
		commonHPager(baseSearch);
		List<XtUserinfo>XtUserinfoList = xtUserinfoService.getXtUserinfoListByCondition(condition);
		PageInfo<XtUserinfo> page = new PageInfo<XtUserinfo>(XtUserinfoList);
		return outPageStr(page,baseSearch);
	}

	/**
	 * 同步至授权中心
	 * @param userinfoEntity
	 */
	@PostMapping(value="/syncOauth")
	@ApiOperation(value="同步至授权中心", notes="同步至授权中心")
	public BaseResult syncOauth(@RequestBody UserinfoEntity userinfoEntity){
		BaseResult baseResult = new BaseResult();
		baseResult.setSuccess(false);
		if(null != userinfoEntity){
			if(StringUtil.isEmpty(userinfoEntity.getXt_userinfo_id())){
				baseResult.setMessage("未能获取到用户id");
				return baseResult;
			}
			Map<String,Object> condition = new HashMap<>();
			condition.put("xt_userinfo_id", userinfoEntity.getXt_userinfo_id().split(","));
			List<XtUserinfo> userinfos = xtUserinfoService.getXtUserinfoList(condition);
			List<UserinfoEntity> userinfoEntities = JsonUtil.toFastList(userinfos,UserinfoEntity.class);
			if(!CollectionUtils.isEmpty(userinfoEntities)) {
				for (UserinfoEntity userinfoEntitys : userinfoEntities) {
					userinfoEntitys.setAccount_type_id(userinfoEntity.getAccount_type_id());
                    userinfoEntitys.setSync(userinfoEntity.getSync());
				}
				baseResult = oauthAccountService.sync(userinfoEntities);
			}
		}
		if(baseResult.getSuccess()){
			aBLogs("用户控制层", "同步至授权中心", "同步至授权中心成功");
			return baseResult;
		}else{
			aBLogs("用户控制层", "同步至授权中心", "同步至授权中心失败");
			return baseResult;
		}
	}

	/**
	 * 查询员工信息列表
	 * @param userinfoEntity
	 */
	@NeedLoginUnAuth
	@PostMapping(value="/users")
	@ApiOperation(value="查询员工信息列表", notes="查询员工信息列表")
	public BaseResult getUsers(@RequestBody UserinfoEntity userinfoEntity){
		if(StringUtil.isEmpty(userinfoEntity.getXt_userinfo_id())){
			return new BaseResult();
		}
		Map<String, Object> condition = new HashMap<>();
		condition.put("xt_userinfo_id",userinfoEntity.getXt_userinfo_id().split(","));
		List<XtUserinfo>XtUserinfoList = xtUserinfoService.getXtUserinfoList(condition);
		return new BaseResult(XtUserinfoList);
	}
}
